import { useState } from 'react';
import pcadata from './pcadata.json';

interface Item {
  label: string;
  value: string;
  children?: Item[];
}
let pcaList: Item[] = [];

function transformData(data) {
  const result: Item[] = [];
  for (const key in data['86']) {
    const item = {
      label: data['86'][key],
      value: key,
      children: [] as any[],
    };
    if (data[key]) {
      for (const subKey in data[key]) {
        const subItem: any = {
          label: data[key][subKey],
          value: subKey,
          children: [],
        };
        if (data[subKey]) {
          for (const leafKey in data[subKey]) {
            subItem.children.push({
              label: data[subKey][leafKey],
              value: leafKey,
            });
          }
        }
        item.children.push(subItem);
      }
    }
    result.push(item);
  }
  return result;
}

/** 获取省市区列表 */
export function getPcaList() {
  if (!pcaList.length) {
    pcaList = transformData(pcadata);
  }
  return pcaList;
}

/**
 * 获取省市区列表 hook
 * const pcaList = usePcaList();
 */
export const usePcaList = () => {
  const [list] = useState(getPcaList());
  /** 省市区列表 */
  return list;
};
